<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="classNo">
              <a-input v-model="model.classNo" placeholder="自动生成编号"  disabled=""></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="说明" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="classDesc">
              <a-input v-model="model.classDesc" placeholder="请输入说明"  ></a-input>
            </a-form-model-item>
          </a-col>
          <template v-if="initPid">
            <a-col :span="8">
              <a-form-model-item label="入节点" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="processIn">
                <j-search-select-tag v-model="model.processIn" :dict="processInOutDict" placeholder="请选择入节点"/>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="出节点" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="processOut">
                <j-search-select-tag v-model="model.processOut" :dict="processInOutDict" placeholder="请选择出节点"/>
              </a-form-model-item>
            </a-col>
          </template>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="工艺路线" :key="refKeys[0]" :forceRender="true">
        <j-editable-table
          :ref="refKeys[0]"
          :loading="mdmProcessRouteDetailTable.loading"
          :columns="mdmProcessRouteDetailTable.columns"
          :dataSource="mdmProcessRouteDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :actionButton="true"
          :actionAddButton="false"
          @added="detailAdded">
          <div slot="buttonBefore">
            <div class="action-button">
              <a-button type="primary" icon="plus" @click="chooseProcessBase" :disabled="formDisabled">新增</a-button>
              <span class="gap"></span>
            </div>
          </div>
        </j-editable-table>
        <j-popup-onl-report ref="processBasePopReport" code="mdm_popup_process_base" multi="true"
                            @ok="processBasePopupCallback"/>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>

import {FormTypes, getRefPromise, VALIDATE_NO_PASSED} from '@/utils/JEditableTableUtil'
import {JEditableTableModelMixin} from '@/mixins/JEditableTableModelMixin'
import {getAction} from "@/api/manage";
import moment from "moment/moment";
import store from "@/store";

export default {
  name: 'MdmProcessRouteClassForm',
  mixins: [JEditableTableModelMixin],
  components: {},
  data() {
    return {
      labelCol: {
        xs: {span: 24},
        sm: {span: 6},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16},
      },
      labelCol2: {
        xs: {span: 24},
        sm: {span: 3},
      },
      wrapperCol2: {
        xs: {span: 24},
        sm: {span: 20},
      },
      model: {
      },
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
      },
      refKeys: ['mdmProcessRouteDetail',],
      tableKeys: ['mdmProcessRouteDetail',],
      activeKey: 'mdmProcessRouteDetail',
      // 工艺路线
      mdmProcessRouteDetailTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '工序',
            key: 'processName',
            type: FormTypes.popup,
            popupCode:"mdm_popup_process_base",
            orgFields: 'id,process_no,process_name,price_type,work_id,standard_hours,prepare_hours,wait_hours,unit',
            destFields: 'processId,processNo,processName,priceType,workId,standardHours,prepareHours,waitHours,unit',
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '序号',
            key: 'seqNo',
            type: FormTypes.inputNumber,
            width: "80px",
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '车间',
            key: 'workshop',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '工作中心',
            key: 'workId',
            type: FormTypes.sel_search,
            dictCode: "mdm_work_center,name,id",
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '标准工时',
            key: 'standardHours',
            type: FormTypes.inputNumber,
            width: "100px",
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '准备工时',
            key: 'prepareHours',
            type: FormTypes.inputNumber,
            width: "100px",
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '等待工时',
            key: 'waitHours',
            type: FormTypes.inputNumber,
            width: "100px",
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '单位',
            key: 'unit',
            type: FormTypes.sel_search,
            dictCode: "mdm_unit,unit_name,unit_code",
            width: "100px",
            placeholder: '请输入${title}',
            defaultValue: '12',
          },
          {
            title: '工序控制码',
            key: 'controlId',
            type: FormTypes.sel_search,
            dictCode: "mdm_process_control,control_name,id",
            width: "140px",
            placeholder: '请输入${title}',
            defaultValue: '1547363324136845314',
          },
          {
            title: '计价类型',
            key: 'priceType',
            type: FormTypes.select,
            dictCode: "mdm_process_price_type",
            width: "140px",
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '操作者',
            key: 'handler',
            type: FormTypes.sel_user,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '模具/工装',
            key: 'mould',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '要求说明',
            key: 'routeDesc',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '工序ID',
            key: 'processId',
            type: FormTypes.hidden,
          },
          {
            title: '工序编号',
            key: 'processNo',
            type: FormTypes.hidden,
          },
        ]
      },
      url: {
        add: "/mdm/processRoute/addRouteClass",
        edit: "/mdm/processRoute/editRouteClass",
        queryById: "/mdm/processRoute/queryRouteClassById",
        genClassNo: "/mdm/processRoute/generateClassNo",
        mdmProcessRouteDetail: {
          list: '/mdm/processRoute/queryProcessRouteDetailByClassId'
        },
      }
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    },
    initMainId: "",
    initPid: "",
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
    processInOutDict(){
      return "mdm_process_route_detail where class_id='" + this.initPid + "',process_name,id";
    }
  },
  created() {
  },
  methods: {
    addBefore() {
      this.model.mainId = this.initMainId;
      this.model.pid = this.initPid;
      this.mdmProcessRouteDetailTable.dataSource = []
      this.generateClassNo();
    },
    getAllTable() {
      let values = this.tableKeys.map(key => getRefPromise(this, key))
      return Promise.all(values)
    },
    // editBefore(record){
    //   record.id = record.classId;
    // },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      this.$nextTick(() => {
      })
      // 加载子表数据
      if (this.model.id) {
        let params = {classId: this.model.id}
        this.requestSubTableData(this.url.mdmProcessRouteDetail.list, params, this.mdmProcessRouteDetailTable)
      }
    },
    //校验所有一对一子表表单
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([]).then(() => {
          resolve(allValues)
        }).catch(e => {
          if (e.error === VALIDATE_NO_PASSED) {
            // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
            this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
          } else {
            console.error(e)
          }
        })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        processRouteDetailList: allValues.tablesValue[0].values,
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    popupCallback(value, row) {
      this.model = Object.assign(this.model, row);
    },
    detailAdded: function (obj) {      let editTable = this.$refs[this.refKeys[0]];
      let seqNo = this.generateSeqNo();
      editTable.setValues([{rowKey: obj.row.id, values: {seqNo: seqNo}}])
    },
    /** 生成工序号 */
    generateSeqNo(){
      let editTable = this.$refs[this.refKeys[0]];
      let rows = editTable.rows;
      let num = 10;
      if(rows.length > 1){
        let lastId = editTable.getCleanId(rows[rows.length-2].id)
        let {values} = editTable.getValuesSync({ validate: false, rowIds: [lastId] });
        num = Number(values[0].seqNo) + 10
      }
      return num
    },
    chooseProcessBase(){
      this.$refs.processBasePopReport.show();
    },
    processBasePopupCallback(rows){
      if(rows && rows.length > 0){
        let processRouteDetailTable = this.$refs[this.refKeys[0]];
        let oldData = processRouteDetailTable.getValuesSync();
        let column = this.mdmProcessRouteDetailTable.columns.find(col=>col.key === 'processName')
        let orgFieldsArr = column.orgFields.split(',');
        let destFieldsArr = column.destFields.split(',');
        let addRow, addData
        for(let i =0; i< rows.length; i++){
          if(!(i === 0 && oldData && oldData.values && oldData.values.length===1 && !oldData.values[0].materialDesc)){
            processRouteDetailTable.add();
          }
          addRow = processRouteDetailTable.rows[processRouteDetailTable.rows.length - 1];
          // key转换
          for(let j=0; j<orgFieldsArr.length; j++){
            rows[i][destFieldsArr[j]] = rows[i][orgFieldsArr[j]];
            if(destFieldsArr[j] !== orgFieldsArr[j]){
              delete rows[i][orgFieldsArr[j]]
            }
          }
          addData = Object.assign({},rows[i])
          processRouteDetailTable.popupCallback(addData.processName, addData, 'processName'+addRow.id, addRow, column)
        }
      }
    },
    /** 生成分类编号 */
    generateClassNo(){
      getAction(this.url.genClassNo, {mainId: this.model.mainId, pid: this.model.pid}).then(res => {
        if (res.success) {
          this.model.classNo = res.result
        };
      })
    },
  }
}
</script>

<style scoped>
  .action-button {
    margin-bottom: 8px;
  }
  .gap {
    padding-left: 8px;
  }
</style>